#include "test.h"
#include "main.h"

class Test_BStorage : public Test
{
	public:
	
	Test_BStorage() {}

	void check()
	{
		string_0000();
		int_0000();
		block_0000();
	}

	void users() {}
	void bench() {}
	

	protected:
	
	void string_0000()
	{
		Memory buffer;
		std::string c = "string check";
		{
			BOStorage s(buffer);
			s << c;
		}
		std::string v;
		{
			BIStorage s(buffer);
			s >> v;
		}
		CHECKSTRING(c,v);
	}


	void int_0000()
	{
		Memory buffer;
		int c = 0x12345678;
		{
			BOStorage s(buffer);
			s << c;
		}
		int v = 0;
		{
			BIStorage s(buffer);
			s >> v;
		}
		CHECKINT(c,v);
	}


	void block_0000()
	{
		const int c1 = 0x12345678;
		const int c2 = 0x77747774;
		const std::string filename = Format("./tmp/%$.bin")%Test::nocolon(PF);
		{
			printf("# %s writing\n",filename.data());
			FileMappingDynamicSegment buffer(filename.data(),true,0666,64*1024);
			{	
				BOStorage s(buffer);
				s << BOStorage::BEGIN << c1 << BOStorage::END << c2;
			}
		}
		
		{
			printf("# %s reading 1\n",filename.data());
			FileMappingConstSegment buffer(filename.data());
			int v1 = 0;
			int v2 = 0;
			{
				BIStorage s(buffer);
				try
				{
					s >> BIStorage::BEGIN >> v1 >> BIStorage::END;
				}
				catch(const Exception & xe)
				{
					printf("# exception %s\n",xe.text().data());
					s >> BIStorage::ABORT;
				}
				s >> v2;
				CHECKINT(c1,v1);
				CHECKINT(c2,v2);
			}
		}

		{
			printf("# %s reading 2\n",filename.data());
			FileMappingConstSegment buffer(filename.data());
			int v2 = 0;
			{
				BIStorage s(buffer);
				s >> BIStorage::BEGIN >> BIStorage::ABORT >> v2;
				CHECKINT(c2,v2);
			}
		}

		{
			printf("# %s reading 3\n",filename.data());
			FileMappingConstSegment buffer(filename.data());
			int v1 = 0;
			int v1bis = 0;
			int v2 = 0;
			{
				BIStorage s(buffer);
				try
				{
					s >> BIStorage::BEGIN >> v1 >> v1bis >> BIStorage::END;
				}
				catch(const Exception & xe)
				{
					printf("# exception %s\n",xe.text().data());
					s >> BIStorage::ABORT;
				}
				s >> v2;
				CHECKINT(c1,v1);
				CHECKINT(c2,v2);
			}
		}


	}




};

REGTEST(Test_BStorage);
